<template>
  <div class="edit">
    <!-- 1.0 头部导航结构 -->
    <van-nav-bar
      title="个人信息编辑"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push({ path: '/' })"
    >
      <template #right>
        <van-icon name="wap-home-o" color="#f00" size="6vw" />
      </template>
    </van-nav-bar>
    <div class="avatar">
      <van-uploader :after-read="afterRead">
        <div class="avatar-img">
          <van-image
            round
            width="100%"
            height="100%"
            :src="info.head_img | imgUrl"
          />
        </div>
      </van-uploader>
    </div>
    <MyCell
      title="昵称"
      :dest="info.nickname"
      @click="nicknameShow = true"
    ></MyCell>
    <MyCell title="密码" dest="***" @click="passwordShow = true"></MyCell>
    <MyCell
      title="性别"
      :dest="info.gender ? '男' : '女'"
      @click="genderShow = true"
    ></MyCell>
    <van-dialog
      v-model="nicknameShow"
      title="修改昵称"
      show-cancel-button
      @confirm="nicknameFn"
    >
      <!-- 记得在 main 里面导入表单结构 -->
      <van-field
        required
        v-model="nicknameTemp"
        label="文本"
        placeholder="请输入新昵称"
      />
    </van-dialog>
    <van-dialog
      v-model="passwordShow"
      title="密码"
      show-cancel-button
      :before-close="beforeClose"
    >
      <!-- 记得在 main 里面导入表单结构 -->
      <van-field
        @click-right-icon="eye"
        :right-icon="downIcon ? 'eye' : 'closed-eye'"
        :type=" downIcon ? 'password': 'text'"
        required
        v-model="passwordOld"
        label="旧密码"
        placeholder="请输入旧密码"
      >
      </van-field>
      <van-field
        type="password"
        required
        v-model="passwordNew"
        label="新密码"
        placeholder="请输入新密码"
      />
    </van-dialog>
    <van-action-sheet
      v-model="genderShow"
      :actions="[
        { name: '男', gender: 1 },
        { name: '女', gender: 0 },
      ]"
      cancel-text="取消"
      close-on-click-action
      @select="genderFn"
    />
  </div>
</template>

<script>
// this.$router.back()  可以实现返回
import MyCell from "../components/MyCell";
import { userParticulars } from "../apis/user.js";
import { uploadFileAPI, userloadAPI } from "../apis/index.js";
export default {
  components: {
    MyCell,
  },
  data() {
    return {
      downIcon : true,
      info: {},
      //昵称
      nicknameShow: false,
      nicknameTemp: "",
      //密码
      passwordShow: false,
      passwordOld: "",
      passwordNew: "",
      //
      genderShow: false,
      actions: [{ name: "男" }, { name: "女" }],
    };
  },
  methods: {
    // 修改用户昵称
    async nicknameFn() {
      // 获取输入框的用户昵称
      if (this.nicknameTemp === "") return this.$notify("请输入昵称，不能为空");
      // 发送请求更新用户昵称
      const res = await userloadAPI(this.$route.query.id, {
        nickname: this.nicknameTemp,
      });
      this.info.nickname = res.data.data.nickname;
      this.$toast.success("昵称更新成功");
    },
    //  修改用户密码 关闭弹出框前自动执行的回调函数，需要在组件上添加 before-close
    async beforeClose(action, done) {
      // console.log(action, done);
      // 如果点击的是确定按钮
      if (action === "confirm") {
        // 检查：用户输入的原密码是否正确
        if (
          this.passwordOld === this.info.password &&
          /^[a-zA-Z0-9~!@#$%^&*_+=-]{3,18}$/.test(this.passwordNew)
        ) {
          // console.log("原密码输入正确，新密码也合法，可以走更新逻辑了");
          // 🔔 主动关闭弹窗
          done();
          // 发送请求更新密码
          const res = await userloadAPI(this.$route.query.id, {
            password: this.passwordNew,
          });
          // console.log(res);
          // 如果修改成功，提示用户
          if (res.data.message === "修改成功") {
            // 由于页面没有刷新，所以修改后的密码也要做一下数据的同步
            this.info.password = this.passwordNew;
            this.$toast.success("密码修改成功");
          }
        } else {
          // console.log("原密码输入错误了~~~");
          // 🔔 阻止弹窗关闭。done(false)
          done(false);
          // 轻提示
          this.$toast.fail("原密码输入错误或密码不合法");
        }
      } else {
        // 关闭弹窗
        done();
      }
    },
    eye() {
      this.downIcon = !this.downIcon
    },
    // 头像
    async afterRead(file) {
      // 此时可以自行将文件上传至服务器
      console.log(file);
      // 上传需要用 FormData 的方式
      const fd = new FormData();
      fd.append("file", file.file);
      // 传进入的参数是一个 FormData 对象
      const res = await uploadFileAPI(fd);
      console.log(res);
      if (res.data.message == "文件上传成功") {
        const imgUrl = res.data.data.url;
        const res2 = await userloadAPI(this.$route.query.id, {
          head_img: imgUrl,
        });
        this.info.head_img = res2.data.data.head_img;
        console.log(res2);
      }
    },
    //性别
    async genderFn(item) {
      // console.log(11);
      console.log(item);
      const res = await userloadAPI(this.$route.query.id, {
        gender: item.gender,
      });
      this.info.gender = item.gender;
      // console.log(res);
    },
  },

  async created() {
    const id = this.$route.query.id;
    const res = await userParticulars(id);
    this.info = res.data.data;
  },
};
</script>

<style lang="less" scoped>
.avatar {
  height: 200px;
  background-color: rgb(196, 237, 245);
  display: flex;
  justify-content: center;
  align-items: center;
  .avatar-img {
    width: 100px;
    height: 100px;
    background-color: rgb(244, 246, 247);
  }
}
</style>